﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace DPSController
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        SerialPort MyPort = new SerialPort();
        string MsgAllMin = "";
        bool MyPortOpen = false;

        public MainWindow()
        {
            InitializeComponent();
            BindController();
            SearchPort();
        }

        void BindController()
        {
            List<string> ls = new List<string>();
            foreach(var a in cons)
            {
                ls.Add(a.ConName);
            }
            ComboBoxModel.ItemsSource = ls;
            if (ComboBoxModel.Items.Count > 0) ComboBoxModel.SelectedIndex = 0;
        }

        /// <summary>
        /// https://zhidao.baidu.com/question/1605146090410918067.html
        /// 
        /// 扫描端口：
        /// https://blog.csdn.net/qq_29377279/article/details/81146081
        /// </summary>
        void SearchPort()
        {
            RegistryKey keyCom = Registry.LocalMachine.OpenSubKey("Hardware\\DeviceMap\\SerialComm");
            if (keyCom != null)
            {
                string[] sSubKeys = keyCom.GetValueNames();
                ComboBoxSerial.Items.Clear();
                foreach (string sName in sSubKeys)
                {
                    string sValue = (string)keyCom.GetValue(sName);
                    ComboBoxSerial.Items.Add(sValue);
                }
                if (ComboBoxSerial.Items.Count > 0) ComboBoxSerial.SelectedIndex = 0;
            }
        }

        #region 控制器型号

        struct MyController
        {
            public string ConName;
            public string MsgHead;
            public string MsgBody;
            public string MsgFoot;
            public int ChannelNum;
            public List<string> Channel;
            public string MsgAllMin;
        }

        static MyController DPS3_24W125_4TS = new MyController
        {
            ConName = "DPS3-24W125-4TS",
            MsgHead = "Sp",
            MsgBody = "0",
            MsgFoot = "#",
            ChannelNum = 4,
            Channel = new List<string>
                {
                    "A","B","C","D"
                },
            MsgAllMin = "SpA0000#SpB0000#SpC0000#SpD0000#",
        };
        static MyController DPS2_24W125_8T = new MyController
        {
            ConName = "DPS2-24W125-8T",
            MsgHead = "S",
            MsgBody = "T",
            MsgFoot = "C#",
            ChannelNum = 8,
            Channel = new List<string>
            {
                "A1", "B2", "C3", "D4", "E5", "F6", "G7", "H8"
            },
            MsgAllMin = "S000T000T000T000T000T000T000T000TC#",
        };

        readonly List<MyController> cons = new List<MyController>()
        {
            DPS3_24W125_4TS,
            DPS2_24W125_8T,
        };

        #endregion
        
        void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //
        }

        private void ButtonSearch_Click(object sender, RoutedEventArgs e)
        {
            SearchPort();
        }

        private void ButtonOpen_Click(object sender, RoutedEventArgs e)
        {
            if (!MyPortOpen)
            {
                MyPort.PortName = ComboBoxSerial.Text;
                MyPort.BaudRate = 19200;
                MyPort.Parity = Parity.None;
                MyPort.DataBits = 8;
                try
                {
                    MyPort.Open();
                    ButtonOpen.Content = "关闭串口";
                    ComboBoxSerial.IsEnabled = false;
                    ComboBoxModel.IsEnabled = false;
                    ButtonSearch.IsEnabled = false;
                    MyPortOpen = true;
                    MyPort.DataReceived += port_DataReceived;
                }
                catch
                {
                    SnackbarMain.MessageQueue.Enqueue("打开串口失败");
                }
            }
            else
            {
                try
                {
                    MyPort.Close();
                    ButtonOpen.Content = "打开串口";
                    ComboBoxSerial.IsEnabled = true;
                    ComboBoxModel.IsEnabled = true;
                    ButtonSearch.IsEnabled = true;
                    MyPortOpen = false;
                    MyPort.DataReceived -= port_DataReceived;
                }
                catch
                {
                    SnackbarMain.MessageQueue.Enqueue("关闭串口失败");
                }
            }
        }

        private void ComboBoxModel_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            MyController mc = cons[(sender as ComboBox).SelectedIndex];
            StackPanel sp = new StackPanel();
            sp.Orientation = Orientation.Horizontal;
            for(int i = 0; i < mc.ChannelNum; i++)
            {
                Slider s = new Slider();
                s.Margin = new Thickness(10, 0, 10, 0);
                s.Minimum = 0;
                s.Maximum = 255;
                s.Name = mc.Channel[i];
                s.Orientation = Orientation.Vertical;
                // 动态修改格式 https://www.cnblogs.com/dotnetHui/p/8398814.html
                s.SetValue(Slider.StyleProperty, Application.Current.Resources["MaterialDesignDiscreteSlider"]);
                s.ValueChanged += Slider_ValueChanged;
                sp.Children.Add(s);
            }
            MsgAllMin = mc.MsgAllMin;
            ConConMain.Content = sp;
        }

        private void Slider_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            var s = sender as Slider;
            MyController con = cons[ComboBoxModel.SelectedIndex];
            switch (con.ConName)
            {
                case "DPS2-24W125-8T":
                    {
                        if (MyPort.IsOpen)
                        {
                            int currentChannel = con.Channel.IndexOf(s.Name);
                            //字符串补0 https://www.cnblogs.com/zhangchaoran/p/8919666.html
                            string v = e.NewValue.ToString().PadLeft(3, '0');
                            char[] msg = MsgAllMin.ToCharArray();
                            char[] vc = v.ToCharArray();
                            msg[1 + 4 * currentChannel] = vc[0];
                            msg[2 + 4 * currentChannel] = vc[1];
                            msg[3 + 4 * currentChannel] = vc[2];
                            MsgAllMin = new string(msg);
                            MyPort.Write(MsgAllMin);
                        }
                        else
                        {
                            SnackbarMain.MessageQueue.Enqueue("串口未开启");
                        }
                    }
                    break;
                case "DPS3-24W125-4TS":
                    {
                        if (MyPort.IsOpen)
                        {
                            //字符串补0 https://www.cnblogs.com/zhangchaoran/p/8919666.html
                            string v = e.NewValue.ToString().PadLeft(3, '0');
                            MsgAllMin = con.MsgHead + s.Name + con.MsgBody + v + con.MsgFoot;
                            MyPort.Write(MsgAllMin);
                        }
                        else
                        {
                            SnackbarMain.MessageQueue.Enqueue("串口未开启");
                        }
                    }
                    break;
            }
        }

        private void ComboBoxSerial_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
    }
}
